import plotly.graph_objects as go
import numpy as np
import sympy as sp

# 定义变量
x = sp.symbols("x")
# 定义函数
f = 2 * x**3 + 3 * x**2 - 12 * x + 7
# 求导
f_diff = sp.diff(f, x)
print("f的导数:", f_diff)
print(f"x=-1时, f的值为:{f.subs(x, -1)}")
print(f"x=-1时, f的导数值为: {f_diff.subs(x, -1)}")

# 画图
x_values = np.linspace(-5, 5, 100)
f_lambda = sp.lambdify(x, f, "numpy")
y = f_lambda(x_values)

fig = go.Figure()
fig.add_trace(go.Scatter(x=x_values, y=y, mode="lines", name="f(x)"))

# 画x=-1的导数
result = f.subs(x, -1)
diff = f_diff.subs(x, -1)
C = result - diff * (-1)
# diff 导数, C 常数 --> f'(-1) = diff * x + C 的线段公式
fun_diff = diff * x + C
x_diff_value = [-5, -1, 5]
y_diff_value = [float(fun_diff.subs(x, value)) for value in x_diff_value]
fig.add_trace(
    go.Scatter(x=x_diff_value, y=y_diff_value, mode="lines", name="导数f'(-1)")
)

fig.show()
